<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-30
 * Time: 09:47
 */

namespace app\api\service\order;


use app\api\model\MoneyOrder;
use app\api\model\User;
use app\api\model\UserMoney;
use app\api\service\Token;
use think\Db;
use think\Exception;

class MoneyOrderSer extends Token
{
    // 订单信息
    private $order;

    // 用户信息
    private $user;

    function __construct($order)
    {
        $this->order = $order;
        $this->user = User::get($this->order['user_id']);
    }

    public function changeStatus()
    {
        if($this->order['status'] == 1) {
            Db::startTrans();
            try {
                // 更新订单状态
                $MoneyOrder = new MoneyOrder();
                $MoneyOrder->save([
                    'status' => 2
                ], ['id' => $this->order['id']]);
                $this->createUserMoney();
                Db::commit();
                return true;
            }
            catch (Exception $ex)
            {
                Db::rollback();
                throw $ex;
                return false;
            }
        } else {
            return true;
        }

    }

    /**
     * 添加余额记录
     * 添加用户余额
     */
    private function createUserMoney()
    {
        $money =  round($this->order['price'] + $this->order['money'],2);
        UserMoney::create([
            'money' => $money,
            'user_id' => $this->user['id'],
            'type' => 1,
            'user_money' => $this->user['money'],
            'order_id' => $this->order['id']
        ]);
        User::where('id',$this->user['id'])->update([
            'money' => round($money + $this->user['money'],2)
        ]);
    }
}